#include "cabplugin.h"

CabPlugin::CabPlugin(){
    qDebug() << "In function "+QString(Q_FUNC_INFO);    
    QString seed = this->toString();
    ID = QCryptographicHash::hash( seed.toAscii(), QCryptographicHash::Md5);

    downloader = new Downloader(this);
    checked = true;

    connect(downloader, SIGNAL(errorOccured(const QString &)),
            this, SLOT(catchError(const QString&)));

    //>>>>>>>>
    //! connecting the downloader.done() signal to member slot finished()
    connect(downloader, SIGNAL(done(const QStringList&)),
            this, SLOT(finished(const QStringList&)));
    //<<<<<<<<


    QStringList html_list = QStringList( QStringList() << "&aacute;" << "&auml;" << "&eacute;"
                                         << "&iacute;" << "&oacute;" << "&ouml;" << "&otilde;"
                                         << "&uacute;" << "&uuml;"<< "&ucirc;" << "&szlig;"
                                         );

    QStringList latin_list = QStringList( QStringList() << "á" << "ä" << "é"
                                          << "í" << "ó" << "ö" << "ő" << "ú"
                                          << "ü" << "ű" << "ß"
                                          );

    QStringList hex_list = QStringList( QStringList() << "%E1" << "%E4" << "%E9"
                                        << "%ED" << "%F3" << "%F6" << "%F5"
                                        << "%FA" << "%FC" << "%FB" << "%DF"
                                        );

    //!Some sites use html encodig for latin strings and QtNetwork unfortunately doesn't support it
    htmlToLatin = utils::toStrPairList( html_list, latin_list );

    /*
     *   Unfortunately some sites use deprecated percentage encoding
     *   so we have to code the search terms, before we pass them to the Downloader
     */
    latinToOldHex = utils::toStrPairList( latin_list, hex_list );

    searchKey=QString("search_term");
    url.setHost("www.cab.u-szeged.hu");

    QStringList lng( QStringList()
                      << "E" << "H" << "G" << "H"
                    );

    LangPairList lplst = ( LangPairList()
                           << qMakePair(ENG, HUN) << qMakePair(HUN, ENG)
                           << qMakePair(GER, HUN) << qMakePair(HUN, GER)                           
                           );

    int i=0;
    foreach( LangPair pair, lplst ) {
        //!populating LangHash        
        supportedLangs[pair] = lngConv.lang2Str(pair.first) +"-"+ lngConv.lang2Str(pair.second) ;
        StrPairList lst;
        lst << StringPair( "max_hits" , "100" ) << StringPair( "mode" , "0" ) << StringPair( "diction" , lng[i] );
        query.insert( pair, lst );
        ++i;
    }

}

bool CabPlugin::search(const State &s) {
       
    if (query.contains(s.dict)) {

        //unfortunately Cab.u-szeged.hu uses deprecated percentage encoding
        //so we have to code the search terms, before we pass them to the Downloader

        QString word = utils::replace( s.word, latinToOldHex );
                
        StrPairList actQuery = query[s.dict];

        switch (s.mode) {
        case 0:
            actQuery[1].second="0";
            break;
        case 1:
            actQuery[1].second="1";
            break;
        case 2:
            actQuery[1].second="2";
            break;
        case 3:
            actQuery[1].second="3";
            break;
        default:
            actQuery[1].second="4";
            break;
        }

        actQuery.prepend( qMakePair( searchKey, word ) );

        url.setPath("/cgi-bin/szotar"+QString((supportedLangs[s.dict].contains(tr("Angol")))?"E":"G"));

        qDebug() <<"ACTQUERY: "<< actQuery;
        url.setQueryItems( actQuery );
        url.setScheme("http");
        qDebug()<<"DICTIONARIES_URL: "<<url.toString();
        downloader->setUrl(url);
        downloader->download();

        return true;

    } else {
        return false;
    }
}

void CabPlugin::finished(const QStringList &lst ) {
       QList< QRegExp > rxlist;

    QRegExp b("<B>");
    QRegExp endb("</B>");

    //*	A QRegExp list is used, to remove unneeded junk from result
    rxlist << b << endb;

    //*	&lst is a QStringList of downloaded html sites, but we only downloaded one site, so we need lst.first()
    QString result = utils::remove( lst.first(), rxlist);

    QRegExp first("<LI>(.+)\\s--&gt;");
    QRegExp second("=[HEG]\">(.+)</A></LI>");
    first.setMinimal(true);
    second.setMinimal(true);


    result = utils::replace( result, htmlToLatin );

    Parser parser( result, first, second );
    hash=parser.parse("\\");

    qDebug()<<"##! In function "+QString(Q_FUNC_INFO)+": Emitting done( hash,url.host() )";
    emit done( hash,url.host() );
}

const LangHash CabPlugin::getLangHash() const{
    return supportedLangs;
}

bool CabPlugin::isChecked(){
    return checked;
}

QString CabPlugin::description(){
    QStringList values=supportedLangs.values();
    return values.join(", ");
}

void CabPlugin::setChecked(bool opt){
    checked = opt;
}

void CabPlugin::catchError(const QString &msg ){
    emit errorOccured( msg );
}

Q_EXPORT_PLUGIN2(cabplugin, CabPlugin)
